package com.luli.controllor;

import com.luli.Utils.SnowflakeIdWorker;
import com.luli.entity.MongoTest;
import com.luli.entity.response.ResponseMsg;
import com.luli.service.MongoTestService;
import com.mongodb.MongoNamespace;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.RenameCollectionOptions;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.luli.Utils.ResponseMsgUtil.getFailMsg;
import static com.luli.Utils.ResponseMsgUtil.getSuccessMsg;

/**
 * 陆离
 * 2022/5/24 17:57:14
 */
@RestController
@Slf4j
@RequestMapping("/Mongo")
@CrossOrigin
public class MongoDataController {
    //https://www.zhangbj.com/p/579.html
    //API https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo-template.save-insert.batch
    @Autowired
    private MongoTestService mongoTestService;
    @Resource
    private MongoTemplate mongoTemplate;

    @GetMapping(value = "/test1")
    public ResponseMsg<?> saveTest(String name, Integer age) {
        try {
            MongoTest mgtest = new MongoTest();
            mgtest.setId(SnowflakeIdWorker.getSnowflakeId());
            mgtest.setAgeS(age);
            mgtest.setNames(name);
            Integer integer = mongoTestService.saveTest(mgtest);
            return getSuccessMsg(null, "成功新增：" + integer + "条数据", null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return getFailMsg(null, "新增失败", e.getMessage());
        }
    }

    /**
     * 根据姓名查询
     * @param name
     * @return
     */
    @GetMapping(value = "/seletTest1")
    public ResponseMsg<?> getTest(String name) {
        try {
            Query query = Query.query(Criteria.where("name").in(name));
            System.out.println(query);
            List<MongoTest> mongoTests = mongoTemplate.find(query, MongoTest.class);
            return getSuccessMsg(null, "", mongoTests);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return getFailMsg(null, "查询失败", e.getMessage());
        }
    }

    /**
     * 根据姓名删除
     * @param name
     * @return
     */
    @GetMapping(value = "/delTest1")
    public ResponseMsg<?> delTest(String name) {
        try {
            Query query = Query.query(Criteria.where("name").is(name));
            System.out.println(query);
            DeleteResult remove = mongoTemplate.remove(query, MongoTest.class);
            return getSuccessMsg(null, "", remove);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return getFailMsg(null, "删除失败", e.getMessage());
        }
    }

    //https://developer.aliyun.com/article/484320
    //https://www.cnblogs.com/hx1098/p/9375090.html
    /*
    mongoTemplate.updateFirest(query, update, "class");
    mongoTemplate.updateMulti(query, update, "class");
        这个两个方法一个是更新满足条件的第一条数据，
        一个是更新所有满足条件的数据，
        它们和upsert的区别就是，
        如果query条件没有筛选出对应的数据，
        那么upsert会插入一条新的数据，
        而update则什么都不会做。和关系型数据库中的merge和update的一样。
     */

    /**
     * 修改指定字段
     * @param name  条件
     * @param updateName 修改后的值
     * @return
     */
    @GetMapping(value = "/updateTest")
    public ResponseMsg<?> updateTest(String name, String updateName) {
        try {
            Query query = new Query();
            Query user = query.addCriteria(Criteria.where("name").is(name));
            List<MongoTest> mongoTests = mongoTemplate.find(user, MongoTest.class);
            if (!mongoTests.isEmpty()){
                Update update = new Update();
                update.set("name",updateName);
                UpdateResult upsert = mongoTemplate.updateMulti(query, update, MongoTest.class);
                return getSuccessMsg(null, "", upsert);
            }else {
                return getFailMsg(null, "数据不存在", null);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return getFailMsg(null, "修改失败", e.getMessage());
        }
    }


    /**
     * in查询
     * @param age
     * @return
     */
    @GetMapping(value = "/selTest")
    public ResponseMsg<?> selTest(String age) {
        List objects = new ArrayList<>();
        objects.add("19");
        objects.add("20");
        Query query = Query.query(Criteria.where("age").in(objects));
        System.out.println(query);
        List<MongoTest> mongoTests = mongoTemplate.find(query, MongoTest.class,"test");
        return getSuccessMsg(null, "", mongoTests);

    }


    @PostMapping(value = "/saveData")
    public ResponseMsg<?> saveData() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("name","lzp");
        dataMap.put("age","18");
//        1) 判断集合是否存在
        boolean pojo011 = mongoTemplate.collectionExists("pojo01");
        MongoCollection<Document> pojo01 = mongoTemplate.createCollection("pojo01");
        log.info("mongodb创建集合===>>>" + pojo01);
        return getSuccessMsg(null, "", null);
    }


    @PostMapping(value = "/uodataName")
    public ResponseMsg<?> uodataName() {
        //修改集合名称
        MongoDatabase db = mongoTemplate.getDb();
        String dbName = db.getName();
        //旧集合名称
        MongoCollection dbCollection = db.getCollection("pojo");
        //新集合名称
        dbCollection.renameCollection(new MongoNamespace(dbName + "." + "pojo1"), new RenameCollectionOptions().dropTarget(true));
        return getSuccessMsg(null, "", null);
    }
}
